/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.gitee.jmash.websocket.client;

import java.io.IOException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.gitee.jmash.websocket.model.Message;
import com.gitee.jmash.websocket.model.MessageDecoder;
import com.gitee.jmash.websocket.model.MessageEncoder;
import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.EncodeException;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;

/**
 * WebSocket Client .
 *
 * @author Juneau
 */
@ClientEndpoint(encoders = { MessageEncoder.class }, decoders = { MessageDecoder.class })
public class SubscribeClient {

  Session session = null;

  private MessageHandler handler;

  /** Basic Client. */
  public SubscribeClient(URI endpointUri) {
    try {
      WebSocketContainer container = ContainerProvider.getWebSocketContainer();
      container.connectToServer(this, endpointUri);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /** Basic OnOpen. */
  @OnOpen
  public void onOpen(Session session) {
    this.session = session;
  }

  public void addMessageHandler(MessageHandler msgHandler) {
    this.handler = msgHandler;
  }

  @OnMessage
  public void processMessage(Message message) {
    System.out.println("Received message in client: " + message);
    handler.handleMessage(message);
  }

  /** Basic sendMessage. */
  public void sendMessage(Message message) {
    try {
      // String text = new MessageEncoder().encode(message);
      this.session.getBasicRemote().sendObject(message);
    } catch (IOException | EncodeException ex) {
      Logger.getLogger(SubscribeClient.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  /** Basic MessageHandler. */
  public static interface MessageHandler {

    public void handleMessage(Message message);

  }
}
